package com.winning.ds.common.util;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * @ClassName : DbUtil
 * @Description : db工具类
 * @Author : zhanglei
 * @Date : 2020/3/24 17:12
 **/
@Slf4j
public class DbUtil {

    public Connection GetDbConnect(String url, String driver, String userName, String password) throws Exception {
        DruidDataSource dataSource = null;
        try {
            dataSource = new DruidDataSource();
            //设置连接参数 (***自己定义传递的参数***)
            dataSource.setUrl(url);
            dataSource.setDriverClassName(driver);
            dataSource.setUsername(userName);
            dataSource.setPassword(password);
            //配置初始化大小、最小、最大
            dataSource.setInitialSize(1);
            dataSource.setMinIdle(1);
            dataSource.setMaxActive(20);
            //连接泄漏监测
            dataSource.setRemoveAbandoned(true);
            dataSource.setRemoveAbandonedTimeout(30);
            //配置获取连接等待超时的时间
            dataSource.setMaxWait(20000);
            //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
            dataSource.setTimeBetweenEvictionRunsMillis(20000);
            //防止过期
            dataSource.setValidationQuery("SELECT 'x'");
            dataSource.setTestWhileIdle(true);
            dataSource.setTestOnBorrow(true);
        } catch (Exception e) {
            log.error("异常：", e);
        }
        // 建立了连接
        Connection con = dataSource.getConnection();
        return con;
    }
}
